<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="lib/socket.io.min.js"></script>
</head>
<body>
    <div id="root">
        <div id="login">
            <input placeholder="请输入昵称" type="text">
        </div>
        <div id="room">
            <h3>欢迎<span style="color:green" id="userNameSpan"></span>的到来，
                当前在线人数<span style="color:red" id="onlineNumSpan"></span>人</h3>
            <input type="text">
            <button>提交</button><br/>
            <textarea cols="100" rows="100"></textarea>
        </div>
    </div>
</body>
<script>
    const login = document.querySelector("#login");
    const room = document.querySelector("#room");
    const loginBtn = login.querySelector("input");
    const userNameSpan = room.querySelector("#userNameSpan");
    const onlineNumSpan = room.querySelector("#onlineNumSpan");
    const subBtn = room.querySelector("button");
    const inpMsg = room.querySelector("input");
    const roomArea = room.querySelector("textarea");

    let ws = null;
    login.style.display = "block";
    room.style.display = "none";
    // 登陆
    loginBtn.onkeyup = function(e){
        if(e.keyCode === 13){
            const userName = this.value.trim();
            if(userName.length ===0){
                alert("请输入昵称");
                return;
            }
            fetch("/login?userName="+this.value.trim())
                .then(value=>value.json())
                .then(res=>{
                    if(res.ok===1){
                        // 成功，可以进入房间
                        login.style.display = "none";
                        room.style.display = "block";
                        userNameSpan.innerHTML = userName;
                        ws = io.connect("/");
                        ws.emit("intoRoom",userName);
                        ws.on("onlineNum",function(num,msg){
                            onlineNumSpan.innerHTML = num;
                            roomArea.value =msg+roomArea.value;
                        })
                        ws.on("sayRoom",function(userName,msg){
                            roomArea.value = userName+":"+msg+"\n"+roomArea.value;
                        })

                        subBtn.onclick = function(){
                            const msg = inpMsg.value.trim();
                            if(msg.length === 0){
                                alert("请输入聊天内容");
                                return;
                            }
                            ws.emit("say",msg);
                            // roomArea.value = userName+":"+msg+"\n"+roomArea.value;
                        }
                    }else{
                        // 失败，不可以进入房间
                        alert("您输入的昵称已经被其它人占用")
                    }
                })
        }
    }
</script>
</html>